package com.ling.pl.security.view.org;

import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.ling.pl.security.feign.DefaultOrgService;
import com.ling.pl.security.model.DefaultOrgVO;
import com.ling.pl.security.model.DefaultPositionVO;
import com.ling.pl.security.model.DefaultUserVO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.List;


/**
 * @author bo.wang
 * @since 2013-1-29
 */
@Component("ling2.orgMaintain")
public class OrgMaintain {
    @Resource
    private DefaultOrgService orgService;

    @DataProvider
    public List<DefaultOrgVO> loadOrgs(String parentId) throws Exception {
        return orgService.loadOrgs(parentId);
    }

    @DataResolver
    public void saveOrgs(Collection<DefaultOrgVO> orgs) {
        for (DefaultOrgVO defaultOrg : orgs) {
            EntityState state = EntityUtils.getState(defaultOrg);

            if (state.equals(EntityState.NEW)) {
                defaultOrg.setCreateDate(new Date());
                orgService.create(defaultOrg);
            }
            if (state.equals(EntityState.MODIFIED) || state.equals(EntityState.MOVED)) {
                orgService.update(defaultOrg.getId(), defaultOrg);
            }

            if (defaultOrg.getChildren() != null) {
                saveOrgs(defaultOrg.getChildren());
            }

            if (state.equals(EntityState.DELETED)) {
                if (countChildren(defaultOrg.getId()) == 0) {
                    orgService.delete(defaultOrg.getId());
                } else {
                    throw new RuntimeException("请先删除子部门");
                }
            }
        }
    }

    @Expose
    public String uniqueCheck(String id) {
        return orgService.uniqueCheck(id);
    }

    @Expose
    public int countChildren(String parentId) {
        return orgService.countChildren(parentId);
    }

    @DataProvider
    public List<DefaultPositionVO> loadPositions(String orgId) {
        return orgService.loadPositions(orgId);
    }

    @DataProvider
    public List<DefaultUserVO> loadUsers(String orgId) {
        return orgService.loadUsers(orgId);
    }
}
